package com.block.datapush.service.apipush;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JiKeBase64Util;
import com.block.datapush.service.apipush.utils.JiKeYouQianUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 79 吉客有钱
 */
@Service
public class JiKeYouQianPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("nameMd5", nameMd5);
        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex",memberSourceInfo.getSex() == 1 ? "1" : "0");
        bizMap.put("cityName", memberSourceInfo.getCity());
        bizMap.put("loanAmount", JiKeYouQianUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("profession",JiKeYouQianUtil.getprofession(memberSourceInfo.getGongzuo()));
        bizMap.put("salaryType", "2");
        bizMap.put("socialSecurity",JiKeYouQianUtil.getSheBao(memberSourceInfo.getShebao()) );
        bizMap.put("providentFund",JiKeYouQianUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("car",JiKeYouQianUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("estate",JiKeYouQianUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("creditCardLimit","0");
        bizMap.put("zhiMaScore",JiKeYouQianUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("huaBeiLimit ",JiKeYouQianUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("weiLiDai","0");
        bizMap.put("jdBaiTiao",JiKeYouQianUtil.getBiaoTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("lifeInsurance",JiKeYouQianUtil.getInsurance(memberSourceInfo.getBaoxian()));
        bizMap.put("monthIncome",JiKeYouQianUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("loanPurpose",JiKeYouQianUtil.getyongtu(memberSourceInfo.getYongtu()));
        bizMap.put("loanTerm",JiKeYouQianUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("degree", JiKeYouQianUtil.getXueli(memberSourceInfo.getXueli()));

        String jsonData = JSON.toJSONString(bizMap);
        String DesData = JiKeBase64Util.encrypt(jsonData,pushApiKeyParam.getApiKey());
        String reqId = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 32);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", LocalDateUtil.getNowDateStr("YYYY-MM-dd HH:mm:ss"));
        paramMap.put("reqId",reqId);
        paramMap.put("data",DesData);

        log.info("【吉客有钱】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap),JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【吉客有钱】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {

            JSONObject data = resultObject.getJSONObject("data");
            Integer dealStatus = data.getInteger("dealStatus");
            String dealDesc = data.getString("dealDesc");
            pushApiResult.setMessage(dealStatus + "|" + dealDesc);

            if (StrUtil.equals(String.valueOf(dealStatus), "1")) {
                String checkNo = data.getString("checkNo");
                extJson.put("checkNo", checkNo);
                pushApiResult.setPushSuccess(true);
                pushApiResult.setOutOrderNo(checkNo);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String checkNo = extJson.getString("checkNo");

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("checkNo", checkNo);
        bizMap.put("name", memberSourceInfo.getRealname());
        bizMap.put("phone", memberSourceInfo.getMobile());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex",memberSourceInfo.getSex() == 1 ? "1" : "0");
        bizMap.put("cityName", memberSourceInfo.getCity());
        bizMap.put("loanAmount", JiKeYouQianUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("profession",JiKeYouQianUtil.getprofession(memberSourceInfo.getGongzuo()));
        bizMap.put("salaryType", "2");
        bizMap.put("socialSecurity",JiKeYouQianUtil.getSheBao(memberSourceInfo.getShebao()) );
        bizMap.put("providentFund",JiKeYouQianUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("car",JiKeYouQianUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("estate",JiKeYouQianUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("creditCardLimit","0");
        bizMap.put("zhiMaScore",JiKeYouQianUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("huaBeiLimit ",JiKeYouQianUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("weiLiDai","0");
        bizMap.put("jdBaiTiao",JiKeYouQianUtil.getBiaoTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("lifeInsurance",JiKeYouQianUtil.getInsurance(memberSourceInfo.getBaoxian()));
        bizMap.put("monthIncome",JiKeYouQianUtil.getShouru(memberSourceInfo.getShouru()));
        bizMap.put("loanPurpose",JiKeYouQianUtil.getyongtu(memberSourceInfo.getYongtu()));
        bizMap.put("loanTerm",JiKeYouQianUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("degree", JiKeYouQianUtil.getXueli(memberSourceInfo.getXueli()));

        JSONObject extParam = new JSONObject();

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String productUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        extParam.put("redirectUrl", productUrl);
        bizMap.put("extParam", extParam);

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("accessoryUrl", pushApiKeyParam.getProtocolUrl());
        jsonObject1.put("accessoryType", "ACCREDIT");
        jsonObject1.put("accessoryFileType", "HTML");
        jsonArray.add(jsonObject1);
        bizMap.put("accessoryList", jsonArray);

        String jsonData = JSON.toJSONString(bizMap);
        String DesData = JiKeBase64Util.encrypt(jsonData,pushApiKeyParam.getApiKey());
        String reqId = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 32);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());
        paramMap.put("timestamp", LocalDateUtil.getNowDateStr("YYYY-MM-dd HH:mm:ss"));
        paramMap.put("reqId",reqId);
        paramMap.put("data",DesData);

        log.info("【吉客有钱】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", requestUrl,  JSON.toJSONString(bizMap),JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【吉客有钱】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String message = resultObject.getString("message");

        pushApiResult.setCode(code + "|" + message);
        pushApiResult.setMessage(message);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {

            JSONObject data = resultObject.getJSONObject("data");
            Integer dealStatus = data.getInteger("dealStatus");
            String dealDesc = data.getString("dealDesc");
            pushApiResult.setMessage(dealStatus + "|" + dealDesc);

            if (StrUtil.equals(String.valueOf(dealStatus), "1")) {
                String applyNo = data.getString("applyNo");
                String redirectUrl = data.getString("redirectUrl");
                pushApiResult.setOutOrderNo(applyNo);
                pushApiResult.setApproveUrl(redirectUrl);

                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(false);
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
                return pushApiResult;
            }
        }

        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject paramJson = JSON.parseObject(paramContent);
        String data = paramJson.getString("data");

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);

        String dataStr = JiKeBase64Util.decrypt(data, merchantBaseInfo.getApiKey());

        JSONObject dataObject = JSON.parseObject(dataStr);
        String applyNo = dataObject.getString("applyNo");
        String dealStatus = dataObject.getString("dealStatus");

        noticeParamDTO.setOutOrderNo(applyNo);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setQueryResult(paramContent);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(applyNo));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        if (StrUtil.equals(dealStatus, "0000")){
            noticeParamDTO.setSettleFlag(true);
            noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        }else{
            noticeParamDTO.setSettleFlag(false);
            noticeParamDTO.setStatus(PushStatusEnum.FAILED.getValue());
        }

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();

        /**
         * {"data":"xydLoPdNQuC2Xi8hPs5qQTb3b+t7uTac5DOGxoRDIZVCV3Z8D5So6Rzb+aXDUe68G1KLJKF+bL/ocPRut+dQpbFllB8bscwH","putSource":"API导流_淘金分期","timestamp":"2023-12-06 17:08:21","reqId":"4646c9790f9640cca841d5e8aed3ad70"}
         */

        jsonObject.put("dealStatus", "0000");
        jsonObject.put("dealDesc", "成功");

        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();

        paramResult.setFilePath("/priprotocol/jikeyouqian");

        JSONObject userInfo = new JSONObject();
        userInfo.put("datetime", LocalDateUtil.getNowDateStr(LocalDateUtil.TOTAL_DATE_TIME));
        userInfo.put("accountNo", memberSourceInfo.getMobile());
        userInfo.put("uid", String.valueOf(memberSourceInfo.getUid()));

        paramResult.setUserInfo(userInfo);

        return paramResult;
    }

    public static void main(String[] args) {

        String data ="xydLoPdNQuC2Xi8hPs5qQTb3b+t7uTac5DOGxoRDIZVCV3Z8D5So6Rzb+aXDUe68G1KLJKF+bL/ocPRut+dQpbFllB8bscwH";

        String decrypt = JiKeBase64Util.decrypt(data, "32e326b5053bc97b895f2c14c228af82");

        System.out.println(decrypt);
    }

}
